#include "adjustment.h"

Adjustment::Adjustment()
{
    brightness = 0;
    contrast = 100;
}

QImage Adjustment::applyAdjustment(QImage &source)
{
    double contrast = (double)this->contrast / 100.0;
    int b = 127 + brightness - 127 * contrast;
    QImage dest = QImage(source);
    int width = source.width();
    int height = source.height();

    if(source.format() == QImage::Format_Indexed8)
    {
        for (int i = 0; i < height; i++)
        {
            uchar* srcPtr = source.scanLine(i);
            uchar* dstPtr = dest.scanLine(i);
            for (int j = 0; j < width; j++, srcPtr++, dstPtr++)
            {
                int temp = *srcPtr * contrast + b;
                temp = temp > 255 ? 255 : temp;
                temp = temp < 0 ? 0 : temp;
                *dstPtr = temp;
            }
        }
    }
    else
    {
        for (int i = 0; i < height; i++)
        {
            QRgb* srcPtr = (QRgb*)source.scanLine(i);
            QRgb* dstPtr = (QRgb*)dest.scanLine(i);
            for (int j = 0; j < width; j++, srcPtr++, dstPtr++)
            {
                int A = qAlpha(*srcPtr);
                int R = qRed(*srcPtr);
                int G = qGreen(*srcPtr);
                int B = qBlue(*srcPtr);
                R = R * contrast + b;
                R = R > 255 ? 255 : R;
                R = R < 0 ? 0 : R;
                G = G * contrast + b;
                G = G > 255 ? 255 : G;
                G = G < 0 ? 0 : G;
                B = B * contrast + b;
                B = B > 255 ? 255 : B;
                B = B < 0 ? 0 : B;
                *dstPtr = qRgba(R, G, B, A);
            }
        }
    }
    return dest;
}
